package com.demo.common.advice;

import com.demo.common.response.Result;
import com.demo.common.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author luogq
 */
@ControllerAdvice(basePackages = "com.demo.mvc.controller")
@Slf4j
public class ResponseHandler implements ResponseBodyAdvice<Object> {

  @Override
  public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
    return true;
  }

  @Override
  public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
    log.info("ControllerAdvice 拦截生效");
    if (o  instanceof String) {
      log.info("ControllerAdvice 拦截String生效");
      return JsonUtil.object2Json(Result.suc(o));
    }
    return Result.suc(o);
  }
}
